$(document).ready(function() {
    var dataSource = new kendo.data.DataSource({
        serverPaging: true,
        serverSorting: true,
        transport: {
            create: {
                url: appBosch.crud.create,
                dataType: "json"
            },
            read: {
                url: appBosch.crud.read,
                dataType: "json"
            },
            update: {
                url: appBosch.crud.update,
                dataType: "json"
            },
            destroy: {
                url: appBosch.crud.destroy,
                dataType: "json"
            },
            parameterMap: function(options, operation) {

                var params = {};
                switch (operation)
                {
                    case 'create':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'read':
                        break;
                    case 'update':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'destroy':
                        params = {id: options.models[0].id};
                        break;
                }
                return params;
            }
        },
        requestEnd: function (e) {
            if (e.type == 'create') {
                if (e.response === false || e.response === null) {
                    kendoAlert('El usuario no pudo ser creado', 'Error');
                    $("#grid").data('kendoGrid').cancelRow();
                } else if (e.response.error) {
                    kendoAlert(e.response.message, 'Error');
                    $("#grid").data('kendoGrid').cancelRow();
                }
            }
        },
        batch: true,
        schema: {
            model: {
                id: "id",
                fields: {
                    nom: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: true,
                            maxNomina: function (input) {
                                if (input.is("[name=nom]")) {
                                    return input.val().length <= 8;
                                }
                                return true;
                            }
                        }
                    },
                    c: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: false
                        }
                    },
                    fn: {
                        editable: false,
                        nullable: false,
                        validation: {
                            required: false
                        }
                    },
                    n: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: true
                        }
                    },
                    ln1: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: true
                        }
                    },
                    ln2: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: false
                        }
                    },
                    ad: {
                        editable: true,
                        nullable: true,
                        defaultValue: new Date(),
                        type: "date",
                        validation: {
                            required: true
                        }
                    },
                    sup: {
                        editable: true,
                        nullable: false,
                        type: "boolean",
                        defaultValue: false
                    },
                    ie: {
                        editable: true,
                        nullable: false,
                        type: "boolean",
                        defaultValue: false
                    },
                    cId: {
                        editable: true,
                        nullable: false,
                        defaultValue: appBosch.categories[0].value
                    },
                    status: {
                        editable: true,
                        nullable: false,
                        defaultValue: appBosch.types[0].value
                    },
                    team: {
                        editable: true,
                        nullable: true,
                        validation: {
                            required: function (input) {
                                if (input.is("[name=team]")) {
                                    if ($('select[name=cId]').val() !== appBosch.categories[appBosch.categories.length-1].value) {
                                        return true;
                                    } else {
                                        return input.val() != null;
                                    }
                                }
                                return true;
                            }
                        }
                    }
                }
            }
        }
    });
    var command = [{
            name: "editii",
            template: "<a title='Editar' class='k-button k-button-icontext k-grid-edit' href=''><i class='fa fa-pencil'></i></a>",
            text: {
                edit: "",
                update: "",
                cancel: "",
                create: 'Agregar usuario'
            }
        }];
    // kaoisama y admin
    if (appBosch.myCategory === 'a2d2df43-9130-11e3-8702-642737866159' ||
            appBosch.myCategory === '6337fa64-cb11-11e3-9ffa-fc4dd44a2aac') {
        command.push(
                {
                    name: "destroy",
                    template: "<a title='Eliminar' class='k-button k-button-icontext k-grid-delete' href=''><i class='fa fa-times'></i></a>"
                },
        {
            text: "Permissions",
            template: "<a href='##' class='k-button k-button-icontext k-grid-Permissions' title='Administrar permisos'><i class='fa fa-bolt'></i></a>",
            click: permissions
        },
        {
            text: "A",
            template: "<a href='##' class='k-button k-button-icontext k-grid-A' title='Asignar área'>A</a>",
            click: areas
        });
    }
    command.push(
            {
                text: "R",
                click: resetPass
            },
    {
        text: "MH",
        template: "<a href='##' class='k-button k-button-icontext k-grid-MH' title='Matriz multihabilidades'><i class='fa fa-list'></i></a>",
        click: mh
    });

    $("#grid").kendoGrid({
        reorderable: true,
        resizable: true,
        filterable: {
            mode: "row"
        },
        columnMenu: true,
        sortable: true,
        selectable: true,
        navigatable: true,
        dataSource: dataSource,
        excel: {
            fileName: "Usuarios.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Usuarios.pdf"
        },
        toolbar: kendo.template($("#templateToolbar").html()),
        dataBound: dataBound,
        columns: [
            {
                command: command,
                title: "Acciones",
                width: 43 * command.length,
                locked: true
            },
            {
                field: "nom",
                title: "Nomina",
                width: 200,
                template: '<img src="/img/workers-mini/#=nom#.jpg"/> #=nom#',
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                },
                locked: true
            },
            {
                field: "c",
                title: "C.U.R.P",
                width: 200,
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                }
            },
            {
                field: "cId",
                title: "Rol",
                width: 230,
                values: appBosch.categories
            },
            {
                field: "fn",
                title: "Nombre completo",
                width: 300,
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                }
            },
            {
                field: "n",
                title: "Nombre(s)",
                hidden: true,
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                }
            },
            {
                field: "ln1",
                title: "Apellido 1",
                hidden: true,
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                }
            },
            {
                field: "ln2",
                title: "Apellido 2",
                hidden: true,
                filterable: {
                    cell: {
                        operator: "contains"
                    }
                }
            },
            {
                field: "status",
                title: "Estatus",
                values: appBosch.types,
                width: 200
            },
            {
                field: "ad",
                title: "Fecha de ingreso",
                width: 200,
                template: "#=kendo.toString(ad, 'd') #",
                editor: dateEditor
            },
            {
                field: "sup",
                title: "Soporte",
                width: 200,
                template: "#if(sup){ #<i class='fa fa-check'></i> #}#"
            },
            {
                field: "ie",
                title: "Externo",
                width: 200,
                template: "#if(ie){ #<i class='fa fa-check'></i> #}#"
            },
            {
                field: 'team',
                title: 'Equipo',
                values: appBosch.teams,
                width: 200,
                hidden: true
            }
        ],
        editable: {
            confirmation: "¿Estas seguro que deseas eliminar este usuario?",
            mode: "popup"
        }
    });
});

function categoryEditor(container, options) {
    var input = $("<input/>");
    input.attr("name", options.field);
    input.appendTo(container);
    input = input.kendoDropDownList({
        dataTextField: 'text',
        dataValueField: 'value',
        dataSource: appBosch.categories
    }).data('kendoDropDownList');
    input.bind('change', function (e) {
        options.model.set('fields.cId.validation.required', this.value() === appBosch.categories[6].value);
    });
}

function dateEditor(container, options) {
    var input = $("<input/>");
    input.attr("name", options.field);
    input.appendTo(container);
    input = input.kendoDatePicker({
        format: "d",
        max: new Date()
    }).data('kendoDatePicker');
}

function dataBound() {
    var filter = this.dataSource.filter();
    this.thead.find(".k-header-column-menu.k-state-selected").removeClass("k-state-selected");
    if (filter) {
        var filteredMembers = {};
        setFilteredMembers(filter, filteredMembers);
        this.thead.find("th[data-field]").each(function() {
            var cell = $(this);
            var filtered = filteredMembers[cell.data("field")];
            if (filtered) {
                cell.find(".k-header-column-menu").addClass("k-state-selected");
            }
        });
    }
}

function setFilteredMembers(filter, members) {
    if (filter.filters) {
        for (var i = 0; i < filter.filters.length; i++) {
            setFilteredMembers(filter.filters[i], members);
        }
    }
    else {
        members[filter.field] = true;
    }
}

function resetPass(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var id = dataItem.id;
    var url = appBosch.urlResetPass + '/' + id;
    $.getJSON(url, {}, function(success) {
        if (success === true) {
            alert('La contraseña se reseteo correctamente');
        } else {
            alert('Ocurrio un error al tratar de resetear la contraseña');
        }
    });
}

function areas(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var userId = dataItem.id;
    var categoryId = dataItem.cId;
    if (categoryId === 'aa0ac014-02c0-11e4-995e-24b6fdfa405b') {
        alert('Acción no permitida para asociados');
        return;
    }
    var title = 'Asignar áreas - ' + dataItem.nom + " - " + dataItem.fn;
    var window = $("#wndAreas");
    var url = [appBosch.urlAreas, userId].join('/');
    if (!window.data("kendoWindow")) {
        window.kendoWindow({
            width: "600px",
            title: title,
            content: url,
            actions: [
                "Close"
            ],
            open: function() {
                this.center();
            }
        });
    }
    else {
        window.data("kendoWindow").refresh(url).title(title).open();
    }
}

function mh(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var dataItemId = dataItem.id;
    var categoryId = dataItem.cId;
    if (categoryId !== 'aa0ac014-02c0-11e4-995e-24b6fdfa405b') {
        alert('Acción solo permitida para asociados');
        return;
    }
    var url = appBosch.urlUserLines + '/' + dataItemId;
    var title = dataItem.nom + " - " + dataItem.fn;
    var window = $("#wndLines");
    if (!window.data("kendoWindow")) {
        window.kendoWindow({
            width: '70%',
            title: title,
            content: url,
            actions: [
                "Close"
            ],
            open: function() {
                this.center();
            }
        });
    }
    else {
        window.data("kendoWindow").refresh(url).title(title).open();
    }
}

function permissions(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var categoryId = dataItem.cId;
    if (categoryId === 'aa0ac014-02c0-11e4-995e-24b6fdfa405b') {
        alert('Acción no permitida para asociados');
        return;
    }
    var userId = dataItem.id;
    var url = [appBosch.urlGetPermissions, userId].join('/');
    $.getJSON(url, {}, function(permissions) {
        $('div#wndPermissions input[name="create"]').prop('checked', permissions.crud.create);
        $('div#wndPermissions input[name="read"]').prop('checked', permissions.crud.read);
        $('div#wndPermissions input[name="update"]').prop('checked', permissions.crud.update);
        $('div#wndPermissions input[name="destroy"]').prop('checked', permissions.crud.destroy);
        $('div#wndPermissions input[name="end"]').prop('checked', permissions.crud.end);
        $('div#wndPermissions input[name="life"]').prop('checked', permissions.crud.life);
        var title = 'PERMISOS - ' + dataItem.nom + " - " + dataItem.fn;
        var window = $("#wndPermissions");
        window.removeClass('hidden');
        if (!window.data("kendoWindow")) {
            window.kendoWindow({
                width: "600px",
                title: title,
                actions: [
                    "Close"
                ],
                open: function() {
                    this.center();
                },
                close: function() {
                    var params = {
                        uId: userId,
                        c: $('div#wndPermissions input[name="create"]').is(':checked'),
                        r: $('div#wndPermissions input[name="read"]').is(':checked'),
                        u: $('div#wndPermissions input[name="update"]').is(':checked'),
                        d: $('div#wndPermissions input[name="destroy"]').is(':checked'),
                        end: $('div#wndPermissions input[name="end"]').is(':checked'),
                        life: $('div#wndPermissions input[name="life"]').is(':checked')
                    };
                    $.get(appBosch.urlSavePermissions, params, function() {

                    });
                }
            });
        }
        else {
            window.data("kendoWindow").title(title).open();
        }
    });
}

function kendoAlert(message, title) {
    var dialog = $('<div id="windowAlert"></div>');
    var temp = kendo.template($('#dialogAlert').html());
    dialog.html(temp({info: message}));
    dialog.kendoWindow({
        title: title,
        modal: true,
        minWidth: 300,
        deactivate: function () {
            dialog.data('kendoWindow').destroy();
        },
        open: function () {
            dialog.on('click', '#aceptButton', function () {
                dialog.data('kendoWindow').close();
            });
        }
    }).data('kendoWindow').open().center();
}
